package com.excu.applicationRunner;


import com.excu.entity.Column;
import com.excu.factory.demo.AutoCreateTableFactory;
import com.excu.factory.enums.TableStrategy;
import com.excu.service.ColumnsService;


import com.excu.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author: Joyce
 *  Logic is justice
 * @since: 2022/05/14-- 1:11
 *  启动时运行自动创建表
 */
@Component
public class BeforeRunner implements ApplicationRunner {
    @Value("${auto.entity.package}")
    private String ps;
    @Value("${auto.source.dbName}")
    private String dbName;
    @Value("${auto.source.delPath}")
    private String path;
    @Value("${auto.source.switchFlag}")
    private String switchFlag;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ColumnsService columnsService;
    @Override
    public void run(ApplicationArguments args) {
       //自动生成sql表
       autoCreateSqlTable();
       //自动注入
      // autoInJect();
    }


    private void autoCreateSqlTable() {

        logger.info("开始生成sql文件");
        logger.info("扫描数据库：{},驼峰是否开启：{},扫描路径：{},存文件路径 {}",dbName,switchFlag,ps,path);
        try {
            AutoCreateTableFactory factory = AutoCreateTableFactory.getInstance(Boolean.parseBoolean(switchFlag));
            factory.initData(ps);
            Map<String, Set<String>> tableSet = factory.getTableSet();
            Map<String, List<Column>> map  = columnsService.getTableInfoBySet(tableSet.get(TableStrategy.ADD.getCode().toString()), dbName);
            Set<String> forceSet = tableSet.get(TableStrategy.FORCE.getCode().toString());
            for (String tableName : forceSet) {
                List<Column> columns = columnsService.getColumns(tableName, dbName);
                if (Objects.isNull(columns)){
                    continue;
                }
                Column table = null;
                if (columns.isEmpty()){
                    table = columnsService.getTable(tableName, dbName);
                }else {
                    table = columns.get(0);
                }
                List<Map<String, Object>> mapTableData = columnsService.getMapTableData(tableName, dbName, 0, 0);
                factory.exportSqlFile(columns,mapTableData,table,path);
            }
            List<String> sqls = factory.getSqls(map);
            if (sqls.size()>0){
                columnsService.execute(sqls);
                //记录新增sql文件
                Properties prop = System.getProperties();
                String os = prop.getProperty("os.name");
                if((os.startsWith("win") || os.startsWith("Win")) && sqls.size()>0){
                    path+="append.sql";
                    Date date = new Date();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String sqlStr="\n-- 时间:"+simpleDateFormat.format(date)+" 数据库名:"+dbName+"--\n";
                    sqlStr+= String.join("\n", sqls);
                    FileUtils.writeFile(path,sqlStr, true);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("生成sql文件完成");
    }


    public void register(){

    }
}
